<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow">
        <div>
          <a-form size="small" :model="pageData" layout="inline">
              <a-form-item label="织布单号" label-col-flex="100px">
                <a-input
                  :style="{ width: '220px' }"
                  allow-clear
                  class="bacClass"
                  placeholder=""
                  v-model="pageData.planOrderCode"
                  @press-enter="huiche"
                />
              </a-form-item>
              <a-form-item label="客户名称" label-col-flex="100px">
                <a-input
                  :style="{ width: '220px' }"
                  allow-clear
                  class="bacClass"
                  placeholder=""
                  v-model="pageData.customName"
                  @press-enter="huiche"
                />
              </a-form-item>
              <a-form-item label="值机员" label-col-flex="100px">
                <a-input
                  :style="{ width: '232px' }"
                  allow-clear
                  class="bacClass"
                  placeholder=""
                  v-model="pageData.clothName"
                  @press-enter="huiche"
                />
              </a-form-item>
              <a-form-item label="值机班组" label-col-flex="100px">
                <a-cascader
                  :options="pageData.deptList"
                  :style="{ width: '220px' }"
                  v-model="pageData.departmentByDuty"
                  class="bacClass"
                  popup-container="html"
                   @press-enter="huiche"
                   allow-clear
                />
              </a-form-item>
              <a-form-item label="楼层" label-col-flex="100px">
                <a-select
                  popup-container="html"
                  class="bacClass"
                  v-model="pageData.storey"
                  :style="{ width: '245px' }"
                  @focus="getArea"
                   @press-enter="huiche"
                  allow-clear
                >
                  <a-option v-for="item in pageData.areaList" :value="item">{{ item }}</a-option>
                </a-select>
              </a-form-item>
              <a-form-item label="落布日期" label-col-flex="100px">
                <a-range-picker
                  @change="onChange"
                  popup-container="html"
                  :style="{ width: '290px' }"
                  class="bacClass"
                  @press-enter="huiche"
                />
              </a-form-item>
              <!-- <a-form-item label="磅布(初检)时间" label-col-flex="100px">
              <a-range-picker
                popup-container="html"
                style="width: 280px"
                class="bacClass"
                v-model="pageData.fistSgcTime"
                @press-enter="huiche"
              />
            </a-form-item> -->
          </a-form>
        </div>
        <div>
          <Toolbar
            :items="store.pageData.btnList"
            @add="addHandler"
            @del="deleteHandler"
            @select="selectHandler"
            @export="exports"
            @exportAll="exportAll"
          >
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
    </template>

    <template #pageTabel>
      <a-spin
        :loading="pageData.pageLoading"
        tip="加载中"
        dot
        style="height: 100%; width: 100%; z-index: 999"
      >
        <AgGridVuesCopys
          :rowHeight="33"
          :headerHeight="33"
          :suppressCopyRowsToClipboard="true"
          :suppressDragLeaveHidesColumns="true"
          :localeText="localeText1"
          rowSelection="multiple"
          @grid-ready="gridReady"
          @columnResized="onColumnResized"
          @columnMoved="onColumnMoved"
          style="height: 100%"
          @columnVisible="onColumnVisible"
          :defaultColDef="defaultColDef"
          @FilterChanged="FilterChangeds"
          class="ag-theme-alpine"
          :rowData="table.dataList"
          :columnDefs="tc"
        >
        </AgGridVuesCopys>
      </a-spin>
    </template>
    <paginationCopys
      :page-size-options="pagingList1"
      :total="total"
      show-total
      show-jumper
      show-page-size
      @change="PageSize"
      @page-size-change="change1"
      style="justify-content: center"
      :page-size="size"
      :current="page"
    />
    <a-drawer
      style="z-index: 999"
      ok-text="保存"
      cancel-text="关闭"
      :drawer-style="{ zIndex: 9999 }"
      :mask-closable="false"
      :width="400"
      :visible="pageData.showAdd"
      :ok-loading="pageData.pageLoading"
      unmountOnClose
      @ok="sideOk"
      @cancel="pageData.showAdd = false"
    >
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" layout="horizontal" :model="dataForm">
          <a-form-item
            label="名称"
            field="productTypeName"
            :rules="[{ required: true, message: '名称必填' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-input class="bacClass" placeholder="" v-model="dataForm.productTypeName" />
          </a-form-item>
          <a-form-item label="备注" field="remark">
            <a-textarea
              class="bacClass"
              placeholder=""
              v-model="dataForm.remark"
              :max-length="400"
              allow-clear
              show-word-limit
            />
            <!-- <a-input class="bacClass" v-model="dataForm.remark" /> -->
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>

<script lang="ts">
import { post } from '@/api/http'
import emitter from '@/hooks/useEventBus'
import { ref, reactive, onMounted, toRefs } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { Form, Message, Modal } from '@arco-design/web-vue'
import { FormInstance } from '@arco-design/web-vue/es/form'
import { String } from 'lodash'
import { baseURL } from '../../../api/axios.config'
import axios from 'axios'
import filedownload from 'js-file-download'
import usePermission from '@/store/modules/permission'
import { useProductionManagementStore } from '@/store/ProductionManagement/OutputSchedule'
import { storeToRefs } from 'pinia'
import { localeText } from '@/api/aggridZw'
import { pagingList } from '@/api/paging'
import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
interface ProdductTypeInfo {
  id: any
  code: string
  productTypeName: string
  // productTypeCode: string
  remark: string
}

export default {
  name: 'OutputSchedule',
  setup() {
    //日期选择器
    const onSelect = (dateString: string[]) => {
      store.pageData.startDateByDuty = dateString[0]
      store.pageData.endDateByDuty = dateString[1]
    }
    const onChange = (val: any) => {
      if (val == undefined || val == null || val == '') {
        store.pageData.startDateByDuty = ''
        store.pageData.endDateByDuty = ''
      } else {
        store.pageData.startDateByDuty = val[0]
        store.pageData.endDateByDuty = val[1]
      }
    }
    const store = useProductionManagementStore()
    const { total, page, size, pageData, selectedRowKeys, table, rowKey, tableColumns } =
      storeToRefs(store)
    function PageSize(val: any) {
      store.page = val
      doRefresh()
    }
    function change1(val: any) {
      store.size = val
      doRefresh()
    }
    const headerShow = ref<boolean>(true)
    async function doRefresh() {
      try {
        store.pageData.pageLoading = true
        updateGridState01()
        const res: any = await store.selectBd()
        if (res.code == 200) {
          gridOption.value.setRowData(res.data.list)
          const totalFabricNun = res.data.list.reduce((s: any, v: any) => {
            return (s += v.fabricNun)
          }, 0)
          const totalJoinConvolution = res.data.list.reduce((s: any, v: any) => {
            return (s += v.joinConvolution)
          }, 0)
          const totalCroppingWeight = res.data.list.reduce((s: any, v: any) => {
            return (s += v.croppingWeight)
          }, 0)
          const totalWeightByEmp = res.data.list.reduce((s: any, v: any) => {
            return (s += v.weightByEmp)
          }, 0)
          const totalPosteriorWeightByEmp = res.data.list.reduce((s: any, v: any) => {
            return (s += v.posteriorWeightByEmp)
          }, 0)
          const totalFabricWeightByEmp = res.data.list.reduce((s: any, v: any) => {
            return (s += v.fabricWeightByEmp)
          }, 0)
          const totalButtonMeterNum = res.data.list.reduce((s: any, v: any) => {
            return (s += v.buttonMeterNum)
          }, 0)
          gridOption.value.setFilterModel(null)
          gridOption.value.setPinnedBottomRowData([
            {
              ckbox: '总计',
              fabricNun: totalFabricNun,
              joinConvolution: totalJoinConvolution,
              croppingWeight: totalCroppingWeight.toString().includes('.')
                ? totalCroppingWeight.toFixed(2)
                : totalCroppingWeight,
              weightByEmp: totalWeightByEmp.toString().includes('.')
                ? totalWeightByEmp.toFixed(2)
                : totalWeightByEmp,
              posteriorWeightByEmp: totalPosteriorWeightByEmp.toString().includes('.')
                ? totalPosteriorWeightByEmp.toFixed(2)
                : totalPosteriorWeightByEmp,
              fabricWeightByEmp: totalFabricWeightByEmp.toString().includes('.')
                ? totalFabricWeightByEmp.toFixed(2)
                : totalFabricWeightByEmp,
              buttonMeterNum: totalButtonMeterNum.toString().includes('.')
                ? totalButtonMeterNum.toFixed(2)
                : totalButtonMeterNum,
            },
          ])
          store.table.dataList = res.data.list
          store.total = res.data.total
        }
      } catch (error) {
        console.error(error)
      } finally {
        store.pageData.pageLoading = false
      }
    }

    const tablediv = ref(null)
    //下拉框得到焦点
    const focusSel = () => {
      selCxAll({ deleteState: 0 })
    }
    //下拉数据
    const options = ref<any>(store.pageData.nameList)
    const loading = ref(false)
    const handleSearch = (value: any) => {
      if (value) {
        const ob = {
          key: value,
          deleteState: 0,
        }
        loading.value = true

        selCxAll(ob)
        options.value = store.pageData.nameList
        loading.value = false
      } else {
        options.value = []
      }
    }

    //下拉框查询
    function selCxAll(val: any) {
      post({
        url: 'product/productType/getProductTypeName',
        data: val,
      }).then(({ data, code }: any) => {
        if (code === 200) {
          store.pageData.nameList = data
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }

    onMounted(() => {
      // 切换tap到本页面执行的方法
      // emitter.on('ProductInfo', () => {
      selCxAll({})
      doRefresh()
      getUserToken()
      // })
    })

    let cxbl = ''
    //查询
    const selectHandler = () => {
      store.page = 1
      cxbl = store.pageData.dropDownData
      doRefresh()
    }
    const queryData = reactive({
      clothType: '',
    })
    const addHandler = () => {
      //清空数据
      for (const key in dataForm) {
        if (key == 'id') {
          dataForm.id = null
        } else {
          dataForm[key] = ''
        }
      }
      store.pageData.showAdd = true
      store.pageData.sideTitle = '新增产品基础资料'
    }

    const dataForm = reactive<ProdductTypeInfo>({
      id: null,
      code: '',
      remark: '',
      // productTypeCode: '',
      productTypeName: '',
    })
    const gridOption = ref()
    const colState = ref()
    const gridReady = (params: any) => {
      gridOption.value = params.api
      colState.value = params.columnApi
    }

    const formRef = ref<FormInstance>()
    const sideOk = () => {
      formRef.value?.validate().then((err) => {
        if (!err) {
          //store.pageData.pageLoading = true;
          if (store.pageData.sideTitle === '新增产品基础资料') {
            post({
              url: 'product/productType/insert',
              data: [dataForm],
            })
              .then((res: any) => {
                if (res.code === 200) {
                  formRef.value?.resetFields()
                  store.pageData.showAdd = false

                  Message.success({
                    content: '新增成功',
                    duration: 5000,
                  })
                } else {
                  Message.error({
                    content: res.message,
                    duration: 5000,
                  })
                }
                doRefresh()
              })
              .finally(() => {
                //store.pageData.pageLoading = false
              })
          } else {
            post({
              url: 'product/productType/update',
              data: [dataForm],
            })
              .then((res: any) => {
                if (res.code === 200) {
                  formRef.value?.resetFields()
                  store.pageData.showAdd = false
                  //清空数据
                  for (const key in dataForm) {
                    if (key == 'id') {
                      dataForm.id = null
                    } else {
                      dataForm[key] = ''
                    }
                  }
                  Message.success({
                    content: '修改成功',
                    duration: 5000,
                  })
                  store.pageData.showAdd = false
                } else {
                  Message.error({
                    content: res.message,
                    duration: 5000,
                  })
                }
                doRefresh()
              })
              .finally(() => {
                store.pageData.pageLoading = false
              })
          }
        }
      })
    }
    const deleteHandler = () => {
      if (gridOption.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return
      }
      Modal.confirm({
        title: '系统提示',
        content: '确认删除选中的数据?',
        onOk() {
          store.pageData.pageLoading = true
          post({
            url: 'product/productType/delete',
            data: gridOption.value.getSelectedRows().map((o: any) => {
              return o.id
            }),
          })
            .then(({ code, data }: any) => {
              if (code === 200) {
                Message.success({
                  content: '删除成功',
                  duration: 5000,
                })
                store.page = 1
                doRefresh()
              } else {
                Message.error({
                  content: '修改失败',
                  duration: 5000,
                })
              }
            })
            .finally(() => {
              store.pageData.pageLoading = false
            })
        },
      })
    }
    const editHandler = (record: ProdductTypeInfo) => {
      dataForm.id = record.id
      dataForm.productTypeName = record.productTypeName
      dataForm.remark = record.remark
      store.pageData.sideTitle = '修改产品类型资料'
      store.pageData.showAdd = true
    }
    //判断是否填写了中文
    const isChiese = (value: string, cb: Function) => {
      return new Promise<void>((resolve) => {
        if (window.encodeURI(value).indexOf('%') !== -1) {
          cb('填写的值不能包含中文！')
        }
        resolve()
      })
    }
    //导出
    const exports = () => {
      // 获取所有勾选的行数据
      const selectedList: any = []
      gridOption.value.forEachNodeAfterFilterAndSort((node: any) => {
        if (node.isSelected()) {
          selectedList.push(node.data)
        }
      })
      if (selectedList.length === 0) {
        Message.error('请先勾选')
        return
      }
      //导出勾选的行为Excel
      const params = {
        fileName: '产量明细报表.xlsx',
        onlySelected: true, //只勾选导出的行数据
      }
      gridOption.value.exportDataAsExcel(params)
    }
    //设置权限
    // ['查询', '新增', '删除', '导出', '导入']
    const permissionStore = usePermission()

    if (permissionStore.hasPermisson('clmx.cx')) {
      store.pageData.btnList.push('查询')
    }
    if (permissionStore.hasPermisson('clmx.dc')) {
      store.pageData.btnList.push('导出')
      store.pageData.btnList.push('全部导出')
    }
    const handleChange = (_data: any) => {
      store.table.dataList = _data
    }

    let tc: any[] = store.tableColumns.map((o: any) => {
      let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed'],
        tooltipField: o.key,
      }
      obj['width'] = 250
      if (o.slotName === 'action') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['lockPosition'] = 'right'
        obj['width'] = 90
        obj['cellRenderer'] = {
          template: `<a-tag class="tagCss" v-if="e" @click="a">修改</a-tag>`,
          setup(props: any) {
            const a = () => {
              editHandler(props.params.data)
            }
            return {
              e: store.pageData.isEdit,
              a,
            }
          },
        }
      }

      return obj
    })

    let a = [
      {
        showRowGroup: 'hide_def',
        field: 'ckbox',
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 100,
        resizable: false,
        filter: false,
        sortable: false,
        minWidth: 50,
        maxWidth: 150,
        lockPosition: 'left',
      },
    ]
    tc = a.concat(tc)
    const defaultColDef = {
      sortable: true,
      resizable: true,
      filter: true,
      //flex: 1
    }
    const huiche = () => {
      doRefresh()
    }
    const localeText1: any = ref(localeText)
    const pagingList1: any = ref(pagingList)
    const { saveGridState: saveGridState01, updateGridState: updateGridState01 } =
      saveOrUpdateGridState01('OutputSchedule-1', gridOption, colState, tc)
    const onColumnMoved = () => {
      saveGridState01()
    }
    const onColumnResized = () => {
      saveGridState01()
    }
    const onColumnVisible = () => {
      saveGridState01()
    }
    const FilterChangeds = (params: any) => {
      let dataList: any = []
      params.api.forEachNodeAfterFilter((row: any) => {
        dataList.push(row.data)
      })
      const totalFabricNun = dataList.reduce((s: any, v: any) => {
        return (s += v.fabricNun)
      }, 0)
      const totalJoinConvolution = dataList.reduce((s: any, v: any) => {
        return (s += v.joinConvolution)
      }, 0)
      const totalCroppingWeight = dataList.reduce((s: any, v: any) => {
        return (s += v.croppingWeight)
      }, 0)
      const totalWeightByEmp = dataList.reduce((s: any, v: any) => {
        return (s += v.weightByEmp)
      }, 0)
      const totalPosteriorWeightByEmp = dataList.reduce((s: any, v: any) => {
        return (s += v.posteriorWeightByEmp)
      }, 0)
      const totalFabricWeightByEmp = dataList.reduce((s: any, v: any) => {
        return (s += v.fabricWeightByEmp)
      }, 0)
      const totalButtonMeterNum = dataList.reduce((s: any, v: any) => {
        return (s += v.buttonMeterNum)
      }, 0)
      gridOption.value.setPinnedBottomRowData([
        {
          ckbox: '总计',
          fabricNun: totalFabricNun,
          joinConvolution: totalJoinConvolution,
          croppingWeight: totalCroppingWeight.toString().includes('.')
            ? totalCroppingWeight.toFixed(2)
            : totalCroppingWeight,
          weightByEmp: totalWeightByEmp.toString().includes('.')
            ? totalWeightByEmp.toFixed(2)
            : totalWeightByEmp,
          posteriorWeightByEmp: totalPosteriorWeightByEmp.toString().includes('.')
            ? totalPosteriorWeightByEmp.toFixed(2)
            : totalPosteriorWeightByEmp,
          fabricWeightByEmp: totalFabricWeightByEmp.toString().includes('.')
            ? totalFabricWeightByEmp.toFixed(2)
            : totalFabricWeightByEmp,
          buttonMeterNum: totalButtonMeterNum.toString().includes('.')
            ? totalButtonMeterNum.toFixed(2)
            : totalButtonMeterNum,
        },
      ])
    }
    const exportAll = () => {
      post({
        url: 'qms/report/exportAllCheckInDetail',
        data: {
          planOrderCode: store.pageData.planOrderCode,
          customName: store.pageData.customName,
          clothName: store.pageData.clothName,
          startDateByDuty: store.pageData.startDateByDuty,
          endDateByDuty: store.pageData.endDateByDuty,
        },
        responseType: 'blob',
      }).then((res) => {
        filedownload(res, '值机员产量明细表.xlsx')
      })
    }
    //获取当前登录账号
    const getUserToken = () => {
      post({
        url: 'admin/acl/user/findUserToken',
      }).then((res: any) => {
        if (res.code === 200) {
          store.pageData.firmId = res.data.data.firmId
          getDept()
        }
      })
    }

    //值机班组下拉
    const getDept = () => {
      post({ url: `org/baCompany/getDepartmentTree?companyId=${store.pageData.firmId} ` }).then((res: any) => {
      if (res.code == 200) {
        store.pageData.deptList = res.data
      }
    })
    }

    //楼层下拉
    const getArea = () => {
      post({
        url: '/planSingle/planSchedul/getMachineAreaPara',
        data: {
          firmId: store.pageData.firmId,
        },
      }).then((res: any) => {
        if (res.code == 200) {
          store.pageData.areaList = res.data
        }
      })
    }
    return {
      getUserToken,
      getDept,
      getArea,
      onChange,
      FilterChangeds,
      saveOrUpdateGridState01,
      saveGridState01,
      updateGridState01,
      onColumnMoved,
      onColumnResized,
      onColumnVisible,
      colState,
      onSelect,
      permissionStore,
      store,
      pagingList1,
      huiche,
      localeText1,
      defaultColDef,
      tc,
      total,
      PageSize,
      change1,
      page,
      size,
      handleChange,
      deleteHandler,
      sideOk,
      formRef,
      dataForm,
      addHandler,
      selectedRowKeys,
      tableColumns,
      table,
      rowKey,
      pageData,
      queryData,
      editHandler,
      selectHandler,
      // inputBlur,
      isChiese,
      exports,
      tablediv,
      options,
      loading,
      handleSearch,
      focusSel,
      headerShow,
      gridReady,
      exportAll,
    }
  },
  components: { Toolbar },
}
</script>
<style scoped lang="less"></style>
